const { spawn } = require('child_process');
const pack = require('./pack.js');

const run = (label, cmd, params) => new Promise((resolve, reject) => {
  const newCmd = process.platform === 'win32' ? 'npm.cmd' : 'npm';
  const proc = spawn(cmd === 'npm' ? newCmd: cmd, params);

  proc.stdout.on('data', (data) => {
    global.console.log(`[${label}]:\n${data}`);
  });

  proc.stderr.on('data', (data) => {
    global.console.error(`[${label}]:\n${data}`);
  });

  proc.on('close', (code) => {
    global.console.log(`[${label}] process exited with code ${code}`);
    if (`${code}` === '0') {
      resolve();
    } else {
      reject(code);
    }
  });
});

run('Flow main', 'npm', ['run', 'buildFlow'])
// run('ls', 'ls', ['-l', 'dist'])
  .then(() => Promise.all([
    run('Flow business', 'npm', ['run', 'buildBusi']),
    run('Flow phone', 'npm', ['run', 'buildPhone']),
  ]))
  .then(() => {
    pack();
  })
  .catch((e) => {
    global.console.error(e);
    process.exit(1);
  })
